package zql.app_jinnang.View;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.AlarmClock;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.iflytek.sunflower.FlowerCollector;
import com.jaeger.library.StatusBarUtil;
import com.joaquimley.faboptions.FabOptions;
import com.kyleduo.switchbutton.SwitchButton;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.ImageLoader;
import com.yuyh.library.imgsel.config.ISListConfig;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import me.gujun.android.taggroup.TagGroup;
import zql.app_jinnang.Bean.Means;
import zql.app_jinnang.Bean.MessageEvent;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Bean.Noteinfo;
import zql.app_jinnang.Prestener.Prestener_edit;
import zql.app_jinnang.Prestener.PresterImp_edit;
import zql.app_jinnang.R;
import zql.app_jinnang.util.CalendarReminderUtils;
import zql.app_jinnang.util.FucUtil;
import zql.app_jinnang.util.JsonParser;

import static zql.app_jinnang.Bean.Means.isphotouri;


public class EditActivity extends AppCompatActivity implements EditActivityImp,View.OnClickListener {
    private PresterImp_edit presterImp_edit;//代理接口
    private FabOptions fabOptions;
    private SwitchButton switchButton_secret;
    private Toolbar toolbar_add;
    private TagGroup tagGroup;
    private List<String> tags;
    private MaterialEditText materialEditText;
    private NoteBean noteBean;//最后加入数据库的数据类
    private static final int REQUEST_CAMERA_CODE = 1;
    private Button iat_recognize,iat_stop,iat_cancel;

    // 语音听写对象
    private SpeechRecognizer mIat;
    // 语音听写UI
    private RecognizerDialog mIatDialog;
    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();

    private Toast mToast;
    private SharedPreferences mSharedPreferences;
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;

    private boolean mTranslateEnable = false;
    private String resultType = "json";

    private boolean cyclic = false;//音频流识别是否循环调用
    int ret = 0; // 函数调用返回值
    private StringBuffer buffer = new StringBuffer();

    Handler han = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x001) {
                executeStream();
            }
        }
    };

    private String date;
    private String time;
    private String detailTime;

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        initprestener();
        initviewanddata();
        presterImp_edit.setBackgroundColorfromUserseting();
        initIntentExtra();
    }

    /**
     * 实现界面实例化
     */
    private void initviewanddata(){
        this.tags=new ArrayList<>();
        this.noteBean=new NoteBean();
        tags.add("<类型>");
        tags.add("<人物>");
        tags.add("<日期>");
        tags.add("<时间>");
        tags.add("<地点>");
        tags.add("<图片>");
        noteBean.setNotetype("null");//默认为null
        noteBean.setPeople("null");
        noteBean.setDate("null");
        noteBean.setTime("null");
        noteBean.setLocation("null");
        noteBean.setPhotopath("null");
        noteBean.setIsshow(true);
        inittoolbarseting();
        initAudioView();
        initfloationgButton();
        inittagegroup();
        initEdittextView();
        initsaveview();
        initSwitchbutton();
        ISNav.getInstance().init(new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });
    }

    /**
     * 实现代理接口
     */
    private void initprestener(){
        presterImp_edit=new Prestener_edit(this);
    }
    /**
     * 监听传入值
     */
    private void initIntentExtra(){
        Intent mintent=getIntent();
        Bundle bundle=mintent.getBundleExtra("data");
        int type=bundle.getInt("type");
        switch (type){
            case 0:
                updateTagsGroup(0,"工作");
                break;
            case 1:
                updateTagsGroup(0,"学习");
                break;
            case 2:
                updateTagsGroup(0,"生活");
                break;
            case 3:
                updateTagsGroup(0,"日记");
                break;
            case 4:
                updateTagsGroup(0,"旅行");
                break;
            case 10:
                Noteinfo noteinfo=(Noteinfo) bundle.getSerializable("noteinfo");
                loadNoteinfotoEdit(noteinfo);
                break;
                default:
                    break;
        }

    }
    /**
     * 修改背景色
     */
    @Override
    public void setbackgroundcolor(List<Integer>list) {
        StatusBarUtil.setColor(this,list.get(0));
        toolbar_add.setBackgroundColor(list.get(1));
    }

    /**
     * //实例化一个edittext
     */
    private void initEdittextView(){
        materialEditText=(MaterialEditText)this.findViewById(R.id.add_noteinfoedittext);
    }
    private void initSwitchbutton(){
        switchButton_secret=(SwitchButton)this.findViewById(R.id.add_switchbutton_secret);
    }

    private void initAudioView(){
        iat_recognize = findViewById(R.id.iat_recognize);
        iat_recognize.setOnClickListener(this);

        iat_stop = findViewById(R.id.iat_recognize);
        iat_stop.setOnClickListener(this);

        iat_cancel = findViewById(R.id.iat_recognize);
        iat_cancel.setOnClickListener(this);
        // 初始化识别无UI识别对象
        // 使用SpeechRecognizer对象，可根据回调消息自定义界面；
        mIat = SpeechRecognizer.createRecognizer(this, mInitListener);

        // 初始化听写Dialog，如果只使用有UI听写功能，无需创建SpeechRecognizer
        // 使用UI听写功能，请根据sdk文件目录下的notice.txt,放置布局文件和图片资源
        mIatDialog = new RecognizerDialog(this, mInitListener);
        mSharedPreferences = getSharedPreferences("com.memory.android.setting", Activity.MODE_PRIVATE);
        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
    }

    /**
     * //实例化保存按钮
     */
    private void initsaveview(){
        TextView saveview=this.findViewById(R.id.add_savefile);
        saveview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                savedNoteinfotoDatabase();
            }
        });
    }
    /**
     * 添加到数据库
     */
    private void savedNoteinfotoDatabase(){
        if (materialEditText.getText().toString().isEmpty()){
            Toast.makeText(EditActivity.this, "输入框为空，请重新输入", Toast.LENGTH_SHORT).show();
        }else {
            noteBean.setNoteinfo(materialEditText.getText().toString());
            noteBean.setCreatetime(Means.getCreatetime());
            if (switchButton_secret.isChecked()){
                presterImp_edit.saveNoteinfotoSecrectDatabase(noteBean);
            }else {
                presterImp_edit.saveNoteinfotoDatabase(noteBean);
            }
            //EventBus.getDefault().post(new MessageEvent(MessageEvent.UPDATE_DATA));
            if(!TextUtils.isEmpty(date)){
                detailTime = date;
            }else{
                detailTime = Means.getCreatetime();
            }
            if(!TextUtils.isEmpty(time)){
                detailTime = detailTime +" "+ time;
            }else{
                detailTime = detailTime + " 0时0分";
            }
            long currentTimeMillis = System.currentTimeMillis();
            if(!TextUtils.isEmpty(detailTime)){
                currentTimeMillis = stringDateToStamp(detailTime);
            }
            CalendarReminderUtils.addCalendarEvent(this,noteBean.getNoteinfo(),noteBean.getNoteinfo(),currentTimeMillis,1);
            finish();
        }
    }

    public static long stringDateToStamp(String dateString){
        long stamp = System.currentTimeMillis();
        try{
            if(!TextUtils.isEmpty(dateString)){
                dateString = dateString.replace("年","-");
                dateString = dateString.replace("月","-");
                dateString = dateString.replace("日","-");
                dateString = dateString.replace("时",":");
                dateString = dateString.replace("分",":");
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");

                Date date= sdf.parse(dateString);
                stamp = date.getTime();
            }
        }catch (Exception e){

        }
        return stamp;
    }



    /**
     * //实例化标签框
     */
    private void inittagegroup(){
        tagGroup=(TagGroup)this.findViewById(R.id.add_tag_group);
        tagGroup.setTags(tags);
        tagGroup.setOnTagClickListener(new TagGroup.OnTagClickListener() {
            @Override
            public void onTagClick(String tag) {
                if (isphotouri(tag)){
                    initphotoshowdialog(tag);
                }else {
                    Toast.makeText(EditActivity.this,tag, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * //实例化floatingbuttond对象
     */
    private void initfloationgButton(){
        fabOptions=(FabOptions)this.findViewById(R.id.add_floatingbutton);
        fabOptions.setButtonsMenu(R.menu.menu_item_add_floatingbutton);
        fabOptions.setOnClickListener(this);
        fabOptions.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                startRecord();
                return false;
            }
        });
    }

    /**
     * //实例化toolbar对象，设置返回按钮，监听返回按钮状态
     */
    private void inittoolbarseting(){
        toolbar_add=(Toolbar)this.findViewById(R.id.toolbar_add);
        setSupportActionBar(toolbar_add);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("");
        toolbar_add.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (materialEditText.getText().toString().isEmpty()){
                    finish();
                }else {
                   initsavenotedialog();
                }
            }
        });
    }

    /**
     * //实例化一个中心dialog输入人物
     */
    private void initcenterpeopledialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        LayoutInflater layoutInflater=LayoutInflater.from(this);
        View centerview=layoutInflater.inflate(R.layout.activity_add_peopledialog,null);
        final TextView add_dialog_ok,add_dialog_cancel;
        final MaterialEditText add_dialog_peole_edit;
        final AlertDialog alertDialog=builder.setView(centerview).create();
        add_dialog_ok=(TextView) centerview.findViewById(R.id.add_dialog_people_ok);
        add_dialog_cancel=(TextView) centerview.findViewById(R.id.add_dialog_people_cancel);
        add_dialog_peole_edit=(MaterialEditText)centerview.findViewById(R.id.add_dialog_edit_people);
        add_dialog_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateTagsGroup(1,add_dialog_peole_edit.getText().toString());
                alertDialog.dismiss();
            }
        });
        add_dialog_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        alertDialog.show();
    }

    /**
     * //实例化地址输入dialog
     */
    private void initcenterlocationdialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        LayoutInflater layoutInflater=LayoutInflater.from(this);
        View centerview=layoutInflater.inflate(R.layout.activity_add_locationdialog,null);
        final TextView add_location_ok,add_location_cancel;
        final MaterialEditText add_dialog_location_edit;
        final AlertDialog alertDialog=builder.setView(centerview).create();
        add_location_ok=(TextView)centerview.findViewById(R.id.add_dialog_location_ok);
        add_location_cancel=(TextView)centerview.findViewById(R.id.add_dialog_location_cancel);
        add_dialog_location_edit=(MaterialEditText)centerview.findViewById(R.id.add_dialog_edit_location);
        add_location_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateTagsGroup(4,add_dialog_location_edit.getText().toString());
                alertDialog.dismiss();
            }
        });
        add_location_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        alertDialog.show();
    }

    /**
     * //实例化一个类型重新选择菜单
     */
    private void initnoteTypeDialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        LayoutInflater layoutInflater=LayoutInflater.from(this);
        View centerview=layoutInflater.inflate(R.layout.activity_add_notetypedialog,null);
        LinearLayout add_dialog_type_work,add_dialog_type_study,add_dialog_type_live,add_dialog_type_diary,add_dialog_type_travel;
        add_dialog_type_work=(LinearLayout)centerview.findViewById(R.id.add_dialog_typenote_work);
        add_dialog_type_diary=(LinearLayout)centerview.findViewById(R.id.add_dialog_typenote_diary);
        add_dialog_type_live=(LinearLayout)centerview.findViewById(R.id.add_dialog_typenote_live);
        add_dialog_type_study=(LinearLayout)centerview.findViewById(R.id.add_dialog_typenote_study);
        add_dialog_type_travel=(LinearLayout)centerview.findViewById(R.id.add_dialog_typenote_travel);
        final AlertDialog alertDialog=builder.setView(centerview).create();
        add_dialog_type_work.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateTagsGroup(0,getString(R.string.note_work));
                alertDialog.dismiss();
            }
        });
        add_dialog_type_diary.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateTagsGroup(0,getString(R.string.note_diary));
                alertDialog.dismiss();
            }
        });
        add_dialog_type_live.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateTagsGroup(0,getString(R.string.note_live));
                alertDialog.dismiss();
            }
        });
        add_dialog_type_study.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateTagsGroup(0,getString(R.string.note_study));
                alertDialog.dismiss();
            }
        });
        add_dialog_type_travel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateTagsGroup(0,getString(R.string.note_travel));
                alertDialog.dismiss();
            }
        });
        alertDialog.show();
    }

    /**
     * //实例化图片拍摄选取对象
     */
    @TargetApi(Build.VERSION_CODES.M)
    private void initphotoseleteActivity(){
        ISListConfig config=new ISListConfig.Builder()
                .multiSelect(false)
                .rememberSelected(false)
                .btnBgColor(Color.WHITE)
                .btnTextColor(Color.BLACK)
                .statusBarColor(getColor(R.color.colorFloatingButton))
                .backResId(R.drawable.icon_back)
                .title("选取图片")
                .titleColor(Color.BLACK)
                .titleBgColor(getColor(R.color.colorFloatingButton))
                .needCamera(true)
                .needCrop(false)
                .cropSize(0,0,400,200)
                .maxNum(9)
                .build();
        ISNav.getInstance().toListActivity(this,config,REQUEST_CAMERA_CODE);
    }

    /**
     * //实例化一个日期选择dialog
     */
    private void initdatecenterdialog(){
        final Calendar calendar=Calendar.getInstance();
        new DatePickerDialog(this,0, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                int year=i1+1;
                updateTagsGroup(2,i+"年"+year+"月"+i2+"日");
            }
        },calendar.get(Calendar.YEAR)
                ,calendar.get(Calendar.MONTH)
                ,calendar.get(Calendar.DAY_OF_MONTH)).show();
    }
    /**
     //实例化一个时间选择dialog
     */
    private void inittimecenterdialog(){
        Calendar calendar=Calendar.getInstance();
        new TimePickerDialog(this,3, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int i, int i1) {
                updateTagsGroup(3,i+"时"+i1+"分");
            }
        }
                ,calendar.get(Calendar.HOUR_OF_DAY)
                ,calendar.get(Calendar.MINUTE)
                ,true).show();
    }
    /**
     //实例化一个显示图片的dialog
     */
    private void initphotoshowdialog(String imagpath){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        LayoutInflater layoutInflater=LayoutInflater.from(this);
        View centerview=layoutInflater.inflate(R.layout.activity_add_photodiaolg,null);
        final ImageView photoimageview;
        final AlertDialog alertDialog=builder.setView(centerview).create();
        photoimageview=(ImageView)centerview.findViewById(R.id.add_dialog_imageview);
        Glide.with(centerview.getContext()).load(imagpath).into(photoimageview);
        photoimageview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        alertDialog.show();
    }
    /**
     实例化一个保存界面弹出的dialog
     */
    private void initsavenotedialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setMessage(R.string.add_dialog_savenote_message);
        builder.setCancelable(true);
        builder.setPositiveButton(R.string.add_dialog_savenote_save, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                savedNoteinfotoDatabase();
                dialogInterface.dismiss();
                finish();
            }
        });
        builder.setNegativeButton(R.string.add_dialog_savenote_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                finish();
            }
        });
        AlertDialog dialog=builder.create();
        dialog.show();
    }
    /**
     * 函数重写区
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==REQUEST_CAMERA_CODE&&resultCode==RESULT_OK&&data!=null){
            List<String>pathlist=data.getStringArrayListExtra("result");
            updateTagsGroup(5,pathlist.get(0).toString());
        }
    }
    @Override
    public void onClick(View view) {
        if( null == mIat ){
            // 创建单例失败，与 21001 错误为同样原因，参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
            this.showTip( "创建对象失败，请确认 libmsc.so 放置正确，且有调用 createUtility 进行初始化" );
            return;
        }
        switch (view.getId()){
            case R.id.add_floatingbutton_people:
                initcenterpeopledialog();
                if (fabOptions.isOpen()){
                    fabOptions.close(null);
                }
                break;
            case R.id.add_floatingbutton_clock:
                inittimecenterdialog();
                if (fabOptions.isOpen()){
                    fabOptions.close(null);
                }
                break;
            case R.id.add_floatingbutton_location:
                initcenterlocationdialog();
                if (fabOptions.isOpen()){
                    fabOptions.close(null);
                }
                break;
            case R.id.add_floatingbutton_photo:
                initphotoseleteActivity();
                if (fabOptions.isOpen()){
                    fabOptions.close(null);
                }
                break;
            case R.id.add_floatingbutton_type:
                initnoteTypeDialog();
                if (fabOptions.isOpen()){
                    fabOptions.close(null);
                }
                break;
            case R.id.add_floatingbutton_time:
                initdatecenterdialog();
                if (fabOptions.isOpen()){
                    fabOptions.close(null);
                }
                break;
            case R.id.iat_recognize:
                startRecord();
                break;
            case R.id.iat_stop:
                mIat.stopListening();
                showTip("停止听写");
                break;
            // 取消听写
            case R.id.iat_cancel:
                mIat.cancel();
                showTip("取消听写");
                break;
            default:
                break;
        }
    }

    /**
     * 修改模式下，加载已经有的记录
     * @return
     */
    private void loadNoteinfotoEdit(Noteinfo noteinfo){
        if (noteinfo.getId()!=null){
            noteBean.setId(noteinfo.getId());
        }
       if (!noteinfo.getNoteinfo().isEmpty()){
            materialEditText.setText(noteinfo.getNoteinfo());
        }
        if (!noteinfo.getNotetype().isEmpty()){
            updateTagsGroup(0,noteinfo.getNotetype());
        }
        if (!noteinfo.getPeople().equals("null")){
            updateTagsGroup(1,noteinfo.getPeople());
        }
        if (!noteinfo.getDate().equals("null")){
            updateTagsGroup(2,noteinfo.getDate());
        }
        if (!noteinfo.getTime().equals("null")){
            updateTagsGroup(3,noteinfo.getTime());
        }
        if (!noteinfo.getLocation().equals("null")){
            updateTagsGroup(4,noteinfo.getLocation());
        }
        if (!noteinfo.getPhotopath().equals("图片")||!noteinfo.getPhotopath().equals("null")){
            updateTagsGroup(5,noteinfo.getPhotopath());
        }
    }

    /**
     * 更新视图
     * @param i
     * @param str
     */
    private void updateTagsGroup(int i,String str){
        if (tags!=null){
            tags.remove(i);
            tags.add(i,str);
        }
        Log.i("liuguangyou","str:"+str);
        switch (i){
            case 0:
                noteBean.setNotetype(str);
                break;
            case 1:
                noteBean.setPeople(str);
                break;
            case 2:
                date = str;
                noteBean.setDate(str);
                break;
            case 3:
                time = str;
                noteBean.setTime(str);
                break;
            case 4:
                noteBean.setLocation(str);
                break;
            case 5:
                noteBean.setPhotopath(str);
                break;
                default:
                    break;
        }
        tagGroup.setTags(tags);
    }
    /**
    获取context
     */
    @Override
    public Context getbasecontext() {
        return this;
    }
    /**
     * 获取application
     */
    @Override
    public Application getapplication() {
        return this.getApplication();
    }


    /**
     * 返回按键事件
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            if (materialEditText.getText().toString().isEmpty()){
                finish();
            }else {
                initsavenotedialog();
            }
        }
        return false;
    }

    @Override
    public void finish() {
        super.finish();
    }



    private void startRecord(){
        buffer.setLength(0);
        materialEditText.setText(null);// 清空显示内容
        mIatResults.clear();
        // 设置参数
        setParam();
        boolean isShowDialog = mSharedPreferences.getBoolean(
                getString(R.string.pref_key_iat_show), true);
        if (isShowDialog) {
            // 显示听写对话框
            mIatDialog.setListener(mRecognizerDialogListener);
            mIatDialog.show();
            showTip(getString(R.string.text_begin));
        } else {
            // 不显示听写对话框
            ret = mIat.startListening(mRecognizerListener);
            if (ret != ErrorCode.SUCCESS) {
                showTip("听写失败,错误码：" + ret);
            } else {
                showTip(getString(R.string.text_begin));
            }
        }
    }

    /**
     * 参数设置
     *
     * @return
     */
    public void setParam() {
        // 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, resultType);

        this.mTranslateEnable = mSharedPreferences.getBoolean( this.getString(R.string.pref_key_translate), false );
        if( mTranslateEnable ){
            mIat.setParameter( SpeechConstant.ASR_SCH, "1" );
            mIat.setParameter( SpeechConstant.ADD_CAP, "translate" );
            mIat.setParameter( SpeechConstant.TRS_SRC, "its" );
        }

        String lag = mSharedPreferences.getString("iat_language_preference",
                "mandarin");
        if (lag.equals("en_us")) {
            // 设置语言
            mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
            mIat.setParameter(SpeechConstant.ACCENT, null);

            if( mTranslateEnable ){
                mIat.setParameter( SpeechConstant.ORI_LANG, "en" );
                mIat.setParameter( SpeechConstant.TRANS_LANG, "cn" );
            }
        } else {
            // 设置语言
            mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
            // 设置语言区域
            mIat.setParameter(SpeechConstant.ACCENT, lag);

            if( mTranslateEnable ){
                mIat.setParameter( SpeechConstant.ORI_LANG, "cn" );
                mIat.setParameter( SpeechConstant.TRANS_LANG, "en" );
            }
        }
        //此处用于设置dialog中不显示错误码信息
        //mIat.setParameter("view_tips_plain","false");

        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000"));

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1000"));

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1"));

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        mIat.setParameter(SpeechConstant.AUDIO_FORMAT,"wav");
        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/msc/iat.wav");
    }

    private void showTip(final String str) {
        mToast.setText(str);
        mToast.show();
    }

    /**
     * 听写UI监听器
     */
    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        public void onResult(RecognizerResult results, boolean isLast) {
            if( mTranslateEnable ){
                printTransResult( results );
            }else{
                printResult(results);
            }

        }

        /**
         * 识别回调错误.
         */
        public void onError(SpeechError error) {
            if(mTranslateEnable && error.getErrorCode() == 14002) {
                showTip( error.getPlainDescription(true)+"\n请确认是否已开通翻译功能" );
            } else {
                showTip(error.getPlainDescription(true));
            }
        }

    };

    /**
     * 听写监听器。
     */
    private RecognizerListener mRecognizerListener = new RecognizerListener() {

        @Override
        public void onBeginOfSpeech() {
            // 此回调表示：sdk内部录音机已经准备好了，用户可以开始语音输入
            showTip("开始说话");
        }

        @Override
        public void onError(SpeechError error) {
            // Tips：
            // 错误码：10118(您没有说话)，可能是录音机权限被禁，需要提示用户打开应用的录音权限。
            if(mTranslateEnable && error.getErrorCode() == 14002) {
                showTip( error.getPlainDescription(true)+"\n请确认是否已开通翻译功能" );
            } else {
                showTip(error.getPlainDescription(true));
            }
        }

        @Override
        public void onEndOfSpeech() {
            // 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
            showTip("结束说话");
        }

        @Override
        public void onResult(RecognizerResult results, boolean isLast) {
            if (resultType.equals("json")) {
                if( mTranslateEnable ){
                    printTransResult( results );
                }else{
                    printResult(results);
                }
            }else if(resultType.equals("plain")) {
                buffer.append(results.getResultString());
                materialEditText.setText(buffer.toString());
                materialEditText.setSelection(materialEditText.length());
            }

            if (isLast & cyclic) {
                // TODO 最后的结果
                Message message = Message.obtain();
                message.what = 0x001;
                han.sendMessageDelayed(message,100);
            }
        }

        @Override
        public void onVolumeChanged(int volume, byte[] data) {
            showTip("当前正在说话，音量大小：" + volume);
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }
    };

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            if (code != ErrorCode.SUCCESS) {
                showTip("初始化失败，错误码：" + code);
            }
        }
    };


    private void printTransResult (RecognizerResult results) {
        String trans  = JsonParser.parseTransResult(results.getResultString(),"dst");
        String oris = JsonParser.parseTransResult(results.getResultString(),"src");

        if( TextUtils.isEmpty(trans)||TextUtils.isEmpty(oris) ){
            showTip( "解析结果失败，请确认是否已开通翻译功能。" );
        }else{
            materialEditText.setText( "原始语言:\n"+oris+"\n目标语言:\n"+trans );
        }

    }

    private void printResult(RecognizerResult results) {
        String text = JsonParser.parseIatResult(results.getResultString());

        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mIatResults.put(sn, text);

        StringBuffer resultBuffer = new StringBuffer();
        for (String key : mIatResults.keySet()) {
            resultBuffer.append(mIatResults.get(key));
        }

        materialEditText.setText(resultBuffer.toString());
        materialEditText.setSelection(materialEditText.length());
    }


    //执行音频流识别操作
    private void executeStream() {
        buffer.setLength(0);
        materialEditText.setText(null);// 清空显示内容
        mIatResults.clear();
        // 设置参数
        setParam();
        // 设置音频来源为外部文件
        mIat.setParameter(SpeechConstant.AUDIO_SOURCE, "-1");
        // 也可以像以下这样直接设置音频文件路径识别（要求设置文件在sdcard上的全路径）：
        // mIat.setParameter(SpeechConstant.AUDIO_SOURCE, "-2");
        //mIat.setParameter(SpeechConstant.ASR_SOURCE_PATH, "sdcard/XXX/XXX.pcm");
        ret = mIat.startListening(mRecognizerListener);
        if (ret != ErrorCode.SUCCESS) {
            showTip("识别失败,错误码：" + ret);
        } else {
            byte[] audioData = FucUtil.readAudioFile(this, "iattest.wav");

            if (null != audioData) {
                showTip(getString(R.string.text_begin_recognizer));
                // 一次（也可以分多次）写入音频文件数据，数据格式必须是采样率为8KHz或16KHz（本地识别只支持16K采样率，云端都支持），
                // 位长16bit，单声道的wav或者pcm
                // 写入8KHz采样的音频时，必须先调用setParameter(SpeechConstant.SAMPLE_RATE, "8000")设置正确的采样率
                // 注：当音频过长，静音部分时长超过VAD_EOS将导致静音后面部分不能识别。
                // 音频切分方法：FucUtil.splitBuffer(byte[] buffer,int length,int spsize);
                mIat.writeAudio(audioData, 0, audioData.length);

                mIat.stopListening();
            } else {
                mIat.cancel();
                showTip("读取音频流失败");
            }
        }
    }

}
